import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Store } from '@ngxs/store';
import { ShopSelector } from '@shop/store/shop.selector';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-modal',
  template: `
    <form nz-form [formGroup]="validateForm" ngxsForm="shop.form">
      <nz-form-item>
        <nz-form-label [nzSpan]="7" nzRequired>名称</nz-form-label>
        <nz-form-control [nzSpan]="12" [nzErrorTip]="nameErrorTpl">
          <input nz-input formControlName="name" placeholder="请输入名称"/>
          <ng-template #nameErrorTpl let-control>
            <ng-container *ngIf="control.hasError('required')">请输入名称!</ng-container>
            <ng-container *ngIf="control.hasError('minlength')">名称长度为2-50位!</ng-container>
          </ng-template>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="7">价格</nz-form-label>
        <nz-form-control [nzSpan]="12">
          <input nz-input formControlName="price" placeholder="请输入价格" type="number"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="7">简介</nz-form-label>
        <nz-form-control [nzSpan]="12" nzHasFeedback>
          <nz-textarea-count [nzMaxCharacterCount]="2000">
            <textarea formControlName="desc" nz-input rows="2" placeholder="请输入描述"></textarea>
          </nz-textarea-count>
        </nz-form-control>
      </nz-form-item>
    </form>
  `,
  styles: [],
})
export class ModalComponent {
  validateForm: FormGroup;

  constructor(
      private fb: FormBuilder,
      private store: Store,
      private ref: NzModalRef,
  ) {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]],
      price: [''],
      desc: [''],
      id: [],
    });
  }
  ngOnInit(){
    this.store.select(ShopSelector.formFlag).subscribe(r => {
      if (!r) this.ref.destroy();
    });
  }
}
